import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { dictGetDictList } from '@/api/public'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    expireTime: '',
    expireFlag: '',
    expireType: '',
    tenantName: '',
    sellerRechargeOfflinePayApply: null,
    ip: '',
    ip_attribution: '',
    userType: '',
    nickName: '',
    userDict: []
  },

  mutations: {
    SET_USER_DICT: (state, userDict) => {
      state.userDict = userDict
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_IP: (state, { ip, ip_attribution }) => {
      state.ip = ip
      state.ip_attribution = ip_attribution
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType
    },
    SET_NICK_NAME: (state, nickName) => {
      state.nickName = nickName
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_EXPIRETIME: (state, expireTime) => {
      state.expireTime = expireTime
    },
    /**存储用户登录信息 */
    SET_EXPIREFLAG: (state, data) => {
      state.expireFlag = data.expireFlag
      state.expireType = data.user.expireType
      state.sellerRechargeOfflinePayApply = data.sellerRechargeOfflinePayApply
      if (data.user.distrId) {
        state.tenantName = data.user.tenantName
      } else {
        state.tenantName = data.user.remark
      }
    }
  },

  actions: {
    SET_USER_DICT({ commit },) {
      // todo:
      // dictGetDictList().then((res) => {
      //   commit('SET_USER_DICT', res.data)
      // })
    },
    SET_AUTH({ commit }, token) {
      commit('SET_TOKEN', token)
      commit('SET_ROLES', [])
    },
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.data.token)
          commit('SET_TOKEN', res.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const user = res.data.user
          sessionStorage.setItem('userId', user.userId)
          const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : user.avatar;
          commit('SET_IP', {
            ip: res.data.ip,
            ip_attribution: res.data.ip_attribution,
          })
          commit('SET_USER_TYPE', res.data.user.userType)
          commit('SET_NICK_NAME', res.data.user.nickName)
          commit('SET_EXPIRETIME', res.data.user.expireTime)
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)

          //SET_EXPIREFLAG
          commit('SET_EXPIREFLAG', res.data)
          if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_PERMISSIONS', res.data.permissions)
            commit('SET_ROLES', res.data.roles)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }


          if (localStorage.getItem('distr')) {
            /**这里超级管理员不做任何操作 */
          } else
            if (!localStorage.getItem('distr') && user.userId == 1) {
              /**userId==1 为超级管理员，默认租户选择为超级管理员租户 */
              localStorage.setItem('qswedr', 1)
              localStorage.setItem('distr', JSON.stringify({ type: "1", distrId: user.distrId }))
              localStorage.setItem('userName', '')
            } else {
              console.log('22222');
              localStorage.setItem('qswedr', 5)
              localStorage.setItem('userName', user.tenantName ? `${user.tenantName}${user.tenantType == '1' ? '(卖家)' : '(供应商)'}` : null)
              localStorage.setItem('distr', JSON.stringify({ type: "5", distrId: user.distrId }))
            }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
